package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:UDP回显服务器练习
 * User: 王圆豪
 * Date: 2025-05-15
 * Time: 16:45
 */
public class UdpEchoServer1 {
    private DatagramSocket socket = null;

    //构造方法，传入端口号
    public UdpEchoServer1(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器开启！");
        while (true) {
            //创建空的的数据报接收请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(requestPacket);
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //处理请求
            String reponse = precess(request);
            //返回响应
            DatagramPacket reponsePacket = new DatagramPacket(reponse.getBytes(),
                    0,reponse.getBytes().length,requestPacket.getSocketAddress());
            socket.send(reponsePacket);

            //打印日志
            System.out.printf("[%s:%d] req: %s, rep %s\n",requestPacket.getAddress(),
                    requestPacket.getPort(), request,reponse);
        }
    }

    private String precess(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer1 server1 = new UdpEchoServer1(9090);
        server1.start();
    }
}
